package lm.concurrency.day5.CAS;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: Min.Liu
 * @Description:
 * @Date: Created in 11:09 2024/11/7
 */
public class AccountSafeTwo implements Account {
    private AtomicInteger balance;

    public AccountSafeTwo(Integer balance) {
        this.balance = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(Integer amount) {
        while (true) {
            int prev = balance.get();
            int next = prev - amount;
            if (balance.compareAndSet(prev, next)) {
                break;
            }
        }
        // 可以简化为下面的方法
         balance.addAndGet(-1 * amount);
    }

}
